package com.bolt.common.web;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * HttpServletResponse帮助类
 *
 * @author michao
 */
public final class ResponseUtil {
    private static final Logger log = LoggerFactory.getLogger(ResponseUtil.class);

    // 输出，返回null
    public static void render(HttpServletResponse response, String content, String type) {
        try {
            response.setContentType(type + ";charset=UTF-8");
            response.setHeader("Pragma", "No-cache");
            response.setHeader("Cache-Control", "no-cache");
            response.setDateHeader("Expires", 0);
            response.getWriter().write(content);
            response.getWriter().flush();

        } catch (IOException e) {
            log.error(e.toString());
        }
    }


    /**
     * 输出文本，返回null
     *
     * @param response
     * @param text
     * @return
     */
    public static void renderText(HttpServletResponse response, String text) {
        render(response, text, "text/plain");
    }

    /**
     * 输出HTML，返回null
     *
     * @param response
     * @param html
     * @return
     */
    public static void renderHtml(HttpServletResponse response, String html) {
        render(response, html, "text/html");
    }

    /**
     * 输出XML，返回null
     *
     * @param response
     * @param xml
     * @return
     */
    public static void render(HttpServletResponse response, String xml) {
        render(response, xml, "text/xml");
    }


    /**
     * 根据字符串输出JSON，返回null
     *
     * @param response
     * @param jsonString
     * @return
     */
    public static void renderJson(HttpServletResponse response, String jsonString) {
        render(response, jsonString, "text/json");
    }


    /**
     * response 输出JSON
     *
     * @param response
     * @param status     response 状态
     * @param jsonString
     */
    public static void output(HttpServletResponse response, Integer status, String jsonString) {
        response.setStatus(status);
        render(response, jsonString);
    }

    public static void renderError(HttpServletResponse response, int errorCode, String errorMsg) {
        try {
            response.sendError(errorCode, errorMsg);
            response.getWriter().write(errorMsg);
            response.getWriter().flush();
        } catch (IOException e) {
            log.error(e.toString());
        }
    }


    /**
     * 设置页面不缓存
     *
     * @param response
     */
    public static void setResponseNoCache(HttpServletResponse response) {
        response.setHeader("progma", "no-cache");
        response.setHeader("Cache-Control", "no-cache");
        response.setHeader("Cache-Control", "no-store");
        response.setDateHeader("Expires", 0);
    }


}
